<template>
  <div class="form-container" style="align-items: baseline; min-height: 70vh ">
    
      <el-card width="1200px">
          <template #header>
            <div class="card-header">
              <h3>使用与测试说明</h3>
            </div>
          </template>
          <span>
            <p>1. 提供已经训练好的Mnist_cnn和Mnist_cnn_dropout模型供选择, 默认为前者。</p>
            <p>2. 后端项目mnist/train.py可重新训练模型, Windows系统使用cuda加速, Mac使用mps加速。</p>
            <p>3. 前端上传图片, 后端项目static/image/mnist_test有鼠标手写的10张图片供测试。</p>
            <p>4. 预训练的两个模型test9_7都会将9错误识别成7; 因为数据集中外国人手写7喜欢加一横, 与9比较像。</p>
            <p>5. Mnit_cnn_dropout模型会将6错误识别成0,  因为测试6字手写出头偏短比较像0。</p>
          </span>
      </el-card>
      <el-divider />
      <el-form>
        <el-card>
          <template #header>
            <div class="card-header">
              <el-select v-model="model" placeholder="请选择模型" style="width: 300px" >
                <el-option label="Mnist_Cnn模型" value= "cnn" />
                <el-option label="Mnist_Cnn_Dropout模型" value= "dropout" />
              </el-select>
            </div>
          </template>
          <el-upload :action="action" :show-file-list="false" :before-upload="beforeUpload" :on-success="handleSuccess">
            <el-button type="primary">上传手写数字图片</el-button>
            <template #tip>
              
              <div style="margin-top: 20px">支持PNG/JPG格式, 建议28x28像素, 要求黑底白字</div>
            </template>
          </el-upload>

        </el-card>

        <br>

        <el-card v-if="result" width="1200px">
          <template #header>
            <div class="card-header">
              <span>识别结果: {{ result.prediction }}</span>
            </div>
          </template>
          <div class="confidence">置信度: {{ result.confidence }}</div>
          <!-- <img :src="result.imageUrl" class="preview-image" /> -->
        </el-card>
      </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage, type UploadFile } from "element-plus";

interface MnistResult {
  prediction: number;
  confidence: string;
}
/**
 * 识别手写数字后端接口地址
 * 项目提供两个模型：
 * 1. dropout: 删除掉一部分权重，以减少过拟合 
"/api/mnist/predict_dropout/"

 * 
 * 2. no dropout: 不删除权重，训练速度更快，但是容易过拟合
 "/api/mnist/predict/"
 * 
 */

const model = ref("");

const action = ref("/api/mnist/predict/"); // 

const result = ref<MnistResult | null>(null);

watch(model, (newVal: string, oldVal: string) => {
  if (newVal === "dropout") {
    action.value = "/api/mnist/predict_dropout/";
  } else {
    action.value = "/api/mnist/predict/";
  }
});
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("请上传图片文件");
    return false;
  }
  return true;
};

const handleSuccess = (response: any) => {
  result.value = {
    ...response,
  };
};
</script>

<style scoped>

</style>